#include "MeshRenderer.h"
#include "RendererHistoryEvent.h"

using namespace std;
using namespace Qt;

/**
 *	Creates a new instance of QGLSurfacesRenderer.
 */
QGLSurfacesRenderer::QGLSurfacesRenderer(QWidget* parent)
                    :QGLWidget(parent)
{
	scale				= 1;
	selection			= NULL;
	selectionHover		= NULL;
	modelFrame			= NULL;
	selectionMode		= NONE;
	zooming				= false;
	animating			= false;
	mouseMoved			= false;
	zoomComplete		= false;
	nextSelectionTime	= clock();
	lastKnownCursor		= Qt::ArrowCursor;
	interpVal           = 0.0;
	reconMeshOpacity	= 0.0;
	renderMode			= RENDER_TOOL;

		// ### DEBUGGING ###
		testEvent = NULL;
}


/**
 *	Destroys this QGLSurfacesRenderer instance.
 */
QGLSurfacesRenderer::~QGLSurfacesRenderer()
{
	// Nothing to do here
}


/**
 *	Sets the rendering opacity for the reconnected parts
 *	of the currently loaded mesh.
 */
void QGLSurfacesRenderer::setReconnectedOpacity(double opacity)
{
	this->reconMeshOpacity = opacity;
	updateGL();
}


/**
 *	Centers the view on whatever coars model is currently 
 *	loaded into the model frame.
 */
void QGLSurfacesRenderer::centerModel( bool zoom )
{
	if( zoom )
		zoomToMesh(*this->modelFrame->coarse);
	this->modelFrame->t.setScenePosition(Vec3f(this->bounds.center), 
		                                 this->bounds.radius);
}


/**
 *	Adds the specified mesh to the list of models that
 *	this renderer will render.
 */
void QGLSurfacesRenderer::setModelFrame(ModelFrame* frame)
{
	this->modelFrame = frame;
	updateGL();
}


/**
 *	Initializes the modelview and projection matrices used
 *  by the transformer in the specified frame
 */
void QGLSurfacesRenderer::initTransformations(ModelFrame* frame)
{
	//check for null
	if( frame )
	{
		frame->t.setInits( 0.6, 45.0 );
		frame->t.setDimensions( (GLfloat)width(), (GLfloat)height() );
		frame->t.updateProjectionMatrix( );
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glGetDoublev(GL_MODELVIEW_MATRIX, frame->t.modelviewMatrix);
	}
}


/**
 *	Activates the specified selection type.
 */
void QGLSurfacesRenderer::activateSelection ( SelectType type )
{
	selectionMode = type;
}


/**
 *	Reverses the specified event using the data in the event.
 */
void QGLSurfacesRenderer::reverseEvent(Event* _event)
{	
	try
	{
		RendererHistoryEvent* historyEvent;

		historyEvent = (RendererHistoryEvent*)_event;
		this->modelFrame->t.setModelview(historyEvent->modelviewMatrix);
		updateGL();
	}
	catch (char* error)
	{
		return;
	}
}


/**
 *	Sets the render mode -> either RENDER_TOOL, RENDER_FLAT or
 *  RENDER_SMOOTH
 */
void QGLSurfacesRenderer::setRenderMode ( int mode )
{	
	renderMode = mode;
	updateGL();
}